import { Spin } from "antd";
import axios from "axios";
import ReactDOM from "react-dom/client";
import React from "react";

// 全局加载状态控制
let loadingCount = 0;                    // 加载计数器
let loadingRoot: ReactDOM.Root | null = null;  // React根节点
let hideTimeout: number | null = null;   // 隐藏定时器

// 显示全屏加载
const showFullScreenLoading = () => {
  // 如果当前没有加载，创建加载界面
  if (loadingCount === 0) {
    // 1. 创建全屏容器
    const loadingContainer = document.createElement('div');
    loadingContainer.id = 'global-loading';
    loadingContainer.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: transparent;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 9999;
      pointer-events: none;
    `;
    document.body.appendChild(loadingContainer);
    
    // 2. 渲染加载组件
    loadingRoot = ReactDOM.createRoot(loadingContainer);
    loadingRoot.render(
      React.createElement('div', {
        style: {
          background: 'rgba(255, 255, 255, 0.95)',
          padding: '20px 30px',
          borderRadius: '8px',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          minWidth: '120px',
          minHeight: '80px'
        }
      }, 
      React.createElement(Spin, { size: "large", tip: "加载中..." })
      )
    );
  }
  // 3. 增加加载计数
  loadingCount++;
};

// 隐藏全屏加载
const hideFullScreenLoading = () => {
  // 1. 减少加载计数
  loadingCount--;
  
  // 2. 如果所有请求都完成，隐藏加载界面
  if (loadingCount <= 0) {
    loadingCount = 0;
    const loadingContainer = document.getElementById('global-loading');
    if (loadingContainer) {
      loadingRoot?.unmount();
      document.body.removeChild(loadingContainer);
      loadingRoot = null;
    }
  }
};

// 延迟隐藏加载（统一2秒延迟）
const delayedHideLoading = () => {
  // 1. 清除之前的定时器（防止重复设置）
  if (hideTimeout) {
    clearTimeout(hideTimeout);
  }
  
  // 2. 设置新的2秒延迟
  hideTimeout = setTimeout(() => {
    hideFullScreenLoading();
    hideTimeout = null;
  }, 2000);
};

const instance = axios.create({
//   baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 1000,
//   headers: {'X-Custom-Header': 'foobar'}
});
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 1. 添加token到请求头
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = token;
    }
    
    // 2. 显示加载动画
    showFullScreenLoading();
    return config;
  }, 
  function (error) {
    // 请求错误时隐藏加载
    hideFullScreenLoading();
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 请求成功：延迟2秒后隐藏加载
    delayedHideLoading();
    return response;
  }, 
  function (error) {
    // 请求失败：延迟2秒后隐藏加载
    delayedHideLoading();
    
    // 错误状态码处理
    const code = error.request.status;
    if (code == 200) {
      console.log('ok');
    } else if (code == 300) {
      console.log('网络轻轻失败');
    } else if (code == 400) {
      console.log('接口出现问题');
    } else if (code == 500) {
      console.log('页面加载成功');
    }
    
    return Promise.reject(error);
  }
);
  export default instance